/**
 * 
 * The MIT License
 * 
 * Copyright (c) 2008 the original author or authors.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.googlecode.gchartjava;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Contains code common to all charts.
 *
 * @author Julien Chastang (julien.c.chastang at gmail dot com)
 */
abstract class AbstractGChart implements GChart {
		
	private static final String LEGEND_PARAM                    = "chdl=";
	private static final String COLOR_PARAM                     = "chco=";
	private static final String SIZE_PARAM                      = "chs=";
	private static final String DATA_EXTENDED_ENCODING_PARAM    = "chd=e:";
	private static final String DATA_SIMPLE_ENCODING_PARAM      = "chd=s:";
	private static final String CHART_FILL_PARAM                = "chf=";

	private final Map<String,String> parameterMap = new HashMap<String, String>();
	
	protected static final String GCHART_URL = "http://chart.apis.google.com/chart";

	private DataEncoding dataEncoding = DataEncoding.EXTENDED;

	/**
	 * 
	 */
	AbstractGChart(){
		addParameter(SIZE_PARAM,"200x125"); //Default chart size.
	}
    
    /**
     * 
     */
    protected final void setData(final List<Data> data){
		final StringBuilder dataParam = new StringBuilder();
		int count = 0;
		for (Data datum : data) {
			if (datum == null) continue;
			datum.setDataEncoding(dataEncoding);
			dataParam.append((count++ == 0) ? datum : "," + datum);
		}
		if (count > 0){
			addParameter((dataEncoding.equals(DataEncoding.EXTENDED)) ? DATA_EXTENDED_ENCODING_PARAM : DATA_SIMPLE_ENCODING_PARAM, dataParam.toString());
		}
    }

	/**
	 * {@inheritDoc}
	 */
	public void setSize(final int x, final int y){
		addParameter(SIZE_PARAM, x + "x" + y);
	}
	
	/**
	 * {@inheritDoc}
	 */
	public final String createURLString() {
		// TODO: There is a problem here that the string may not be necessarily
		// reproducible. A LinkedHashMap would fix the problem, but break all
		// the tests which would have to be rewritten. At some point this should
		// be tackled.
		prepareData();
		String url = getBaseURLString();
		StringBuilder params = new StringBuilder();
		for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
			params.append("&" + entry.getKey() + "" + entry.getValue());
		}
		return url + params;
	}

	/**
	 * {@inheritDoc}
	 */
	public final String createURLForHTML() {
		return createURLString().replaceAll("&", "&amp;");
	}
	
	/**
	 * Internal method to set chart colors.
	 */
	protected final void setColors(final List<Color> colors) {
		final StringBuilder colorParam = new StringBuilder();
		int count = 0;
		for (Color color : colors) {
			if (color == null) continue;
			colorParam.append((count++ == 0) ? color : "," + color);
		}
		if (count > 0){
			addParameter(COLOR_PARAM, colorParam.toString());
		}
	}
	
	
	/**
	 * Internal method to set chart legends.
	 */
	protected final void setLegends(final List<String> legends){
		final StringBuilder legendParam = new StringBuilder();
		int count = 0;
		for (String legend : legends) {
			if (legend == null) continue;
			final String l = legend.replaceAll("\\s", "+");
			legendParam.append((count++ == 0) ? l : "|" + l);
		}
		if(count > 0)
		  addParameter(LEGEND_PARAM, legendParam.toString());
	}
		
	/**
	 * {@inheritDoc}
	 */
	public void setBackgroundFill(final Fill fill){
		String value = parameterMap.get(CHART_FILL_PARAM);
		if (value == null){
			addParameter(CHART_FILL_PARAM, "bg," + fill);
		}
		else{
			value += "|" +  "bg," + fill;
			addParameter(CHART_FILL_PARAM, value);
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	public final void setDataEncoding(final DataEncoding dataEncoding) {
		this.dataEncoding = dataEncoding;
	}
	
	/**
	 * Convenience method for adding parameters to request.
	 */
	protected final void addParameter(final String key, final String value){
		  parameterMap.put(key, value); 
	}
	
	/**
	 * Convenience method for getting parameters out of paramter map.
	 */
	protected String getParameter(final String key){
		return parameterMap.get(key);
	}
	
	/**
	 * Prepare data for URL String formation.
	 */
	protected abstract void prepareData();
	
	/**
	 * Return the base URL String for the chart type.
	 */
	protected abstract String getBaseURLString();
}
